from django.db import models
from django.contrib.auth.models import AbstractUser
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData

from django.conf import settings
from . import constants

# Create your models here.


class User(AbstractUser):
    """自定义用户模型类"""
    mobile = models.CharField(verbose_name="手机号", max_length=64, unique=True)
    # 增加邮箱验证字段
    email_active = models.BooleanField(default=False, verbose_name='邮箱验证状态')

    class Meta:
        db_table = 'tb_users'
        verbose_name = "手机号"
        verbose_name_plural = verbose_name

    def generate_email_token(self):
        """对用户的邮箱进行加密处理"""
        serializer = Serializer(settings.SECRET_KEY, constants.SAVE_EMAIL_USER_TOKEN_EXPIRES)

        data = {
            "id": self.id,
            "email": self.email
        }
        token = serializer.dumps(data).decode()
        # 生成用户验证链接地址
        verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token
        return verify_url

    # 因为在类的内部,所以调用方法的方式只能通过类对象或者实例对象,而由于视图中没有实例对象,只能通过类进行调用,有由于该方法没有使用到实例对象或者类对象本身,可以定义为静态方法
    @staticmethod
    def check_email_token(token):
        """对用户的邮箱进行解密处理"""
        serializer = Serializer(settings.SECRET_KEY, constants.SAVE_EMAIL_USER_TOKEN_EXPIRES)
        # 调用loads进行解密
        try:
            data = serializer.loads(token)
        except BadData:
            return None
        else:
            # 3.取出参数中的用户信息
            user_id = data.get("id")
            email = data.get("email")
            # 4.对用户的信息进行查询
            try:
                user = User.objects.get(id=user_id, email=email)
            except User.DoesNotExist:
                return None
            else:
                return user
